# -*- coding:utf-8 -*-
# -------------------------------------------------------------------------------
# Description:  
# Reference:
# Author: 安智军
# Date:   2021/12/15
# -------------------------------------------------------------------------------
import yaml
from common.logger import logger


class ReadYaml:
    @staticmethod
    def read(file_path):
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                data = yaml.safe_load(f)
                return data
        except Exception as e:
            logger.exception(f"请查看文件是否正确，异常信息是{str(e)}")
            return None

    @staticmethod
    def write_yaml(data,file_path):
        # file_path = basepath + '/testData/%s' % file_name
        ''' 向yaml文件中写入数据'''
        with open(file_path,encoding="utf-8",mode='w') as f:
            return yaml.dump(data,stream=f,allow_unicode=True)

    @staticmethod
    def update_yaml(file_path,key,value):
        """向yaml中修改数据"""
        # file_path = basepath +'/testData/%s'%file_name
        logger.info(f'正在修改数据，修改的文件名称为:{file_path},修改的键为:{key}，修改的键为:{value}')
        doc = ReadYaml.read(file_path)
        doc['headers'][key] = value
        ReadYaml.write_yaml(doc,file_path)
        logger.info("修改后的数据===》{}".format(doc))

if __name__ == '__main__':

    from common.utils import project_dir
    file_name = "test_B2C_purchase_warehousing_Process.yml"
    test_data_path = project_dir + "/testData/" + file_name
    headers_dict = ReadYaml.read(test_data_path)

    # path =r"D:\接口自动化v2.0\pytest_yaml_study_v1/config/headers.yml"
    # key ="Authorization"
    # value ="51651635"
    # ReadYaml.update_yaml(path,key,value)
    # print(ReadYaml.read(path))
    # headers_dict =headers_dict['headers']
    # print(headers_dict)
    # print(headers_dict['Authorization'])

